﻿
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using SerialPortExample.Model;

namespace SerialPortExamples
{
    public class Logger
    {
        public static Logger logger;

        private string dir = @"C:/PSOM/Log/";

        private string path = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".log";

        private int maxLog = 300;
        public ObservableCollection<string> Logs { get; set; } = new ObservableCollection<string>();

        private readonly object _lock = new object();
        
        public Logger(string path)
        {
            if (File.Exists(path)) throw new Exception($"The file {path} already exists!");
            if (path != null) this.path = path;
            if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
            File.Create(dir + this.path).Close();
            this.path = dir + this.path;
        }

        public static Logger GetInstance(string path = null)
        {
            if (logger == null) logger = new Logger(path);
            return logger;
        }

        public void WriteException(Exception ex)
        {
            string message = $"Error: {ex.Message}\nStack Trace: {ex.StackTrace}";
            SaveToTxt(message);
            WriteToUi(message);
        }

        public void WriteLog(string message)
        {
            SaveToTxt(message);
            WriteToUi(message);
        }

        public void WriteByteArray(byte[] arr, int len = Int16.MaxValue)
        {
            int idx = 0;
            string message = string.Empty;
            foreach (byte b in arr)
            {
                message += b.ToString("x2") + " ";
                if (++idx > len) break;
            }
            SaveToTxt(message);
            WriteToUi(message);
        }

        public void WriteLogAsync(string message)
        {
            SaveToTxt(message);
            Application.Current.Dispatcher.Invoke(() =>
            {
                WriteToUi(message);
            });
        }

        public void WriteToUi(string message)
        {
            Logs.Add(message);
            if (Logs.Count >= maxLog) Logs.RemoveAt(0);
        }

        private void SaveToTxt(string message)
        {
            lock (_lock)
            {
                File.AppendAllText(path, message + "\n");
            }
        }



    }



}
